package admin.forms;

import helpers.StringHelper;

import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import admin.models.CategoryModel;

import entities.Category;


public class CategoryForm {
	public static TreeMap<String, Object> checkValid(HttpServletRequest request, Category category) {
		TreeMap<String, Object> form = new TreeMap<String, Object>();
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String id = (String) request.getParameter("id");
		String name = (String) request.getParameter("name");
		category.setId(id);
		
		if (name == null || name.isEmpty()) {
			check.put("name", "Name is not null.");
			category.setName("");
		} else {
			category.setName(name);
		}
		
		if (name != null && !name.isEmpty()) {
			String alias = StringHelper.replace(name);
			CategoryModel categoryModel = CategoryModel.getInstance();
			if (!alias.isEmpty() && alias.equalsIgnoreCase(category.getAlias())) {
				category.setAlias(alias);
			} else if (alias.isEmpty() || categoryModel.checkAliasExists(alias)) {
				check.put("name", "Category with this name already exists.");
				category.setAlias(alias);
			} else {
				category.setAlias(alias);
			}
		}
		
		form.put("checkValid", check);
		form.put("category", category);
		
		return form;
	}
}
